using BasicData.Application.Services.BasicModel;
using BasicData.Application.Services.BOM;
using BasicData.Application.Services.Customer;
using BasicData.Application.Services.Line;
using BasicData.Application.Services.Material;
using BasicData.Application.Services.Product;
using BasicData.Application.Services.Supplier;
using BasicData.Application.Services.Workshop;
using BasicData.Domain.Entities;
using BasicData.Infrastructure.Repositories;
using Consul;
using NLog.Web;
using SqlSugar;
using System.Net;
using Yitter.IdGenerator;
using StackExchange.Redis;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    var a = Path.Combine(AppContext.BaseDirectory, "BasicData.Api.xml");
    o.IncludeXmlComments(a, true);
});

builder.Services.AddControllers();
//// SqlSugar 注册
//builder.Services.AddScoped<ISqlSugarClient>(sp =>
//    new SqlSugarClient(new ConnectionConfig
//    {
//        ConnectionString = builder.Configuration.GetConnectionString("Oracle"),
//        DbType = DbType.Oracle,
//        IsAutoCloseConnection = true
//    }));

// SqlSugar 注册
builder.Services.AddScoped<ISqlSugarClient>(sp =>
    new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("conn"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute,
       MoreSettings=new ConnMoreSettings()
       {
           IsAutoRemoveDataCache = true,
           IsAutoDeleteQueryFilter = true,
       }
    }));

YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
builder.Services.AddAutoMapper(typeof(MyMapper));
builder.Services.AddScoped<IWorkshopServices, WorkshopServices>();
builder.Services.AddScoped<ILineServices, LineServices>();
builder.Services.AddScoped<IMaterialServices, MaterialServices>();
builder.Services.AddScoped<IProductServices, ProductServices>();
builder.Services.AddScoped<ISupplierServices, SupplierServices>();
builder.Services.AddScoped<ICustomerServices, CustomerServices>();
builder.Services.AddScoped<IBOMServices, BOMServices>();

// 仓储与服务注册
builder.Services.AddScoped(typeof(IBasicModelRepository<>), typeof(BasicModelRepository<>));
builder.Services.AddScoped(typeof(IBasicModelAppService<>), typeof(BasicModelAppService<>));
builder.Host.UseNLog();
builder.Services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(cfg =>
{
    cfg.Address = new Uri("http://120.26.197.100:8500");
}));

// Redis 哨兵模式集成
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
    // 读取 Redis 配置
    var configuration = builder.Configuration.GetSection("Redis");
    var sentinels = configuration["Sentinels"].Split(','); // 哨兵节点列表
    var serviceName = configuration["ServiceName"];         // 主节点名称
    var password = configuration["Password"];               // Redis 密码
    var defaultDb = int.Parse(configuration["DefaultDatabase"] ?? "0"); // 默认数据库

    // 构建哨兵配置
    var options = new ConfigurationOptions
    {
        ServiceName = serviceName, // 指定哨兵监控的主节点名
        Password = password,       // 认证密码
        DefaultDatabase = defaultDb, // 默认数据库
        TieBreaker = "",            // 禁用 TieBreaker
        CommandMap = CommandMap.Sentinel, // 使用 Sentinel 命令集
        AbortOnConnectFail = false        // 连接失败时不抛异常
    };
    // 添加所有哨兵节点
    foreach (var sentinel in sentinels)
    {
        options.EndPoints.Add(sentinel);
    }
    // 切换为默认命令集，允许正常操作 Redis
    options.CommandMap = CommandMap.Default;
    options.AllowAdmin = true; // 允许管理命令
    // 连接哨兵并自动发现主节点，返回连接实例
    return ConnectionMultiplexer.Connect(options);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapControllers();

app.MapGet("/health", () => Results.Ok("Ok"));

var consulClient = app.Services.GetRequiredService<IConsulClient>();
var registration = new AgentServiceRegistration
{
    ID = $"BasicData-{Guid.NewGuid()}",
    Name = "BasicData",
    Address = "120.26.197.100",
    Port = 8089, // 请根据实际端口调整
    //Address = "localhost",
    //Port = 7274, // 请根据实际端口调整
    Check = new AgentServiceCheck
    {
        HTTP = $"http://120.26.197.100:8089/health",
        Interval = TimeSpan.FromSeconds(10),
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1) // 可选：健康检查失败多久后自动移除
    }
};


using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
    db.CodeFirst.InitTables(typeof(BOMModel));
    db.CodeFirst.InitTables(typeof(CustomerModel));
    db.CodeFirst.InitTables(typeof(LineModel));
    db.CodeFirst.InitTables(typeof(MaterialModel));
    db.CodeFirst.InitTables(typeof(ProductModel));
    db.CodeFirst.InitTables(typeof(SupplierModel));
    db.CodeFirst.InitTables(typeof(WorkshopModel));
    db.CodeFirst.InitTables(typeof(UnitModel));
    db.CodeFirst.InitTables(typeof(BomSparepart));
    // 其他初始化...
}
consulClient.Agent.ServiceRegister(registration).Wait();

app.Run();
